import AMapLoader from '@amap/amap-jsapi-loader';
import {reactive} from 'vue'
//请求城市名称
const getCitySuggestions = (keyword) => {
  return new Promise((resolve, reject) => {
    window._AMapSecurityConfig = {
      securityJsCode: '23d45164cfc2f815f5b659ab29f2b927'
    };

    AMapLoader.load({
      key: '2f13fbf16769972e3a8f7b24bbc3f8de',
      version: '2.0'
    })
      .then((AMap) => {
        AMap.plugin('AMap.Weather', () => {
          const weather = new AMap.Weather();
          weather.getForecast(`${keyword}`, (error, data) => {
            if (error) {
              reject(error)
            } else {
              resolve(data.city);
            }
          });
        });
      })
      .catch((error) => {
        console.error('Failed to load AMap:', error);
        reject(error);
      });
  });
};


//请求城市天气数据

const getCityWeather = (city) => {
  return new Promise((resolve,reject) => {
    window._AMapSecurityConfig = {
      securityJsCode: '23d45164cfc2f815f5b659ab29f2b927',
      }
        AMapLoader.load({
        key: '2f13fbf16769972e3a8f7b24bbc3f8de',
        version: '2.0',
      }).then((AMap) => {
        /* console.log('AMap :>> ', AMap); */
  
          // 创建天气查询实例
          AMap.plugin('AMap.Weather', () => {
            const weather = new AMap.Weather();
            // 获取城市的天气信息
            weather.getForecast(`${city}`, (error, data) => {
              if (error) {
                reject(error)
              } else {
                resolve(data.forecasts)
              }
            });
          });
        }).catch((error) => {
          console.error('Failed to load AMap:', error);
        });
  })
}

//获取实时天气数据
const getTimeWeather = (city) => {
  return new Promise((resolve,reject) => {
    window._AMapSecurityConfig = {
      securityJsCode: '23d45164cfc2f815f5b659ab29f2b927',
      }
        AMapLoader.load({
        key: '2f13fbf16769972e3a8f7b24bbc3f8de',
        version: '2.0',
      }).then((AMap) => {
        /* console.log('AMap :>> ', AMap); */
  
          // 创建天气查询实例
          AMap.plugin('AMap.Weather', () => {
            const weather = new AMap.Weather();
            // 获取城市的天气信息
            weather.getLive(`${city}`, (error, data) => {
              if (error) {
                reject(error)
              } else {
                console.log(data,999999);
                resolve(data)
              }
            });
          });
        }).catch((error) => {
          console.error('Failed to load AMap:', error);
        });
  })
}
export { getCitySuggestions,getCityWeather,getTimeWeather};